/**
 * Copyright (C), 2015-2020, XXX有限公司
 * <p>
 * FileName: SecurityConfig
 * <p>
 * Author:   Brill
 * <p>
 * Date:     2020/2/17/017 12:20
 * <p>
 * Description: security配置类
 * <p>
 * History:
 *
 * <author>          <time>          <version>          <desc>
 * <p>
 * 作者姓名           修改时间           版本号              描述
 */


package cn.yuhh.config;


import cn.yuhh.entity.Hr;
import cn.yuhh.entity.RespBean;
import cn.yuhh.service.HrService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.bind.annotation.ResponseStatus;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 〈一句话功能简述〉<br>
 * 〈security配置类〉
 *
 * @author Brill
 * @create 2020/2/17/017
 * @since 1.0.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private HrService hrService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MyFilter myFilter;

    @Autowired
    private MyDecisionManager myDecisionManager;



    /**
     * 添加用户
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(hrService);
    }

    /**
     * 配置过滤
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //所有请求都需要认证
                .anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setAccessDecisionManager(myDecisionManager);
                        o.setSecurityMetadataSource(myFilter);
                        return o;
                    }
                })
                //从表单认证
                .and().formLogin().usernameParameter("username").passwordParameter("password")
                //登陆处理的URL
                .loginProcessingUrl("/doLogin")
                //登陆页面
                .loginPage("/login")
                //登陆成功
                .successHandler(new AuthenticationSuccessHandler() {
                    /**
                     * 登陆成功回调
                     *
                     * @param req:  请求信息
                     * @param resp: 响应
                     * @param auth: 用户信息
                     * @throws IOException
                     * @throws ServletException
                     */
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                        ////登陆成功返回JSON
                        //resp.setContentType("application/json;charset=utf-8");
                        //PrintWriter writer = resp.getWriter();
                        //
                        ////得到用户信息中的HR对象
                        //Hr hr = (Hr) auth.getPrincipal();
                        //RespBean respBean = RespBean.ok("登陆成功", hr);
                        //
                        ////返回给前端
                        //String s = objectMapper.writeValueAsString(respBean);
                        //writer.write(s);
                        //
                        //writer.flush();
                        //writer.close();

                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Hr hr = (Hr) auth.getPrincipal();
                        hr.setPassword(null);
                        RespBean ok = RespBean.ok("登录成功!", hr);
                        String s = objectMapper.writeValueAsString(ok);
                        out.write(s);
                        out.flush();
                        out.close();
                    }
                })
                //登陆失败
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {

                        ////登陆失败返回JSON
                        //resp.setContentType("application/json;charset=utf-8");
                        //PrintWriter writer = resp.getWriter();
                        //
                        //
                        //RespBean respBean = RespBean.error("登陆失败", e);
                        //
                        ////返回给前端
                        //writer.write(objectMapper.writeValueAsString(respBean));
                        //
                        //writer.flush();
                        //writer.close();

                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        RespBean respBean = RespBean.error("登录失败!");
                        if (exception instanceof LockedException) {
                            respBean.setMessage("账户被锁定，请联系管理员!");
                        } else if (exception instanceof CredentialsExpiredException) {
                            respBean.setMessage("密码过期，请联系管理员!");
                        } else if (exception instanceof AccountExpiredException) {
                            respBean.setMessage("账户过期，请联系管理员!");
                        } else if (exception instanceof DisabledException) {
                            respBean.setMessage("账户被禁用，请联系管理员!");
                        } else if (exception instanceof BadCredentialsException) {
                            respBean.setMessage("用户名或者密码输入错误，请重新输入!");
                        }
                        out.write(objectMapper.writeValueAsString(respBean));
                        out.flush();
                        out.close();
                    }
                }).permitAll().and()
                //注销
                .logout().logoutSuccessHandler(new LogoutSuccessHandler() {
            @Override
            public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                writer.write(objectMapper.writeValueAsString(RespBean.ok("注销成功!")));
                writer.flush();
                writer.close();
            }
        }).permitAll().and().csrf().disable();

    }
}
